package com.betterwood.dragon.worms;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import com.betterwood.dragon.entity.Result;
import com.betterwood.dragon.entity.Site;
import com.betterwood.dragon.entity.dto.SearchDTO;
import com.betterwood.dragon.utils.TimeUtil;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class FJ {
    // 福济可用
    public static String login(Site site) {
        log.info("#########################################");
        log.info("############START LOGIN TO FJ############");
        String contextState = "EMPTY";

        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));
            BrowserContext context = browser.newContext();

            // Open new page
            Page page = context.newPage();

            // Go to http://www.fuji-pharm.cn/
            page.navigate(site.getSiteUrl());

            page.click(".logo_phone");

            page.click("text=登录");

            page.click("[placeholder=\"账号\"]");

            // page.fill("[placeholder=\"账号\"]", "01340800000");
            page.fill("[placeholder=\"账号\"]", site.getUserName());

            page.click("[placeholder=\"密码\"]");

            // page.fill("[placeholder=\"密码\"]", "01340800000");
            page.fill("[placeholder=\"密码\"]", site.getPassWord());

            page.waitForNavigation(() -> {
                page.click("text=登录 记住密码 注册 忘记密码 >> button");
            });

            contextState = context.storageState();
            log.info("############END OF LOGIN TO FJ#############");

        } catch (RuntimeException e) {
            e.printStackTrace();

        }
        return contextState;
    }

    public static List<Result> fetchProduct(Site site, SearchDTO search) {
        log.info("#######################################");
        log.info("############START FETCH FROM FJ########");

        // List<Result> res = getList(site, search);
        List<Result> initList = new ArrayList<>();
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(true));
            String storageState = site.getLoginInfo();
            BrowserContext context = browser.newContext(new Browser.NewContextOptions().setStorageState(storageState));

            // Open new page
            Page page = context.newPage();

            page.navigate("http://www.fuji-pharm.cn/");
            log.info("********KEYWORD********");
            log.info(search.getKeywordStr());
            log.info("********KEYWORD********");

            page.click("#search");
            page.fill("#search", search.getKeywordStr());
            page.waitForNavigation(() -> {
                page.click("#searchButtom");
            });

            page.waitForTimeout(1500);
            String content = page.innerHTML("#allsea_comm");
            String pager = page.innerHTML("#DivPages");
            // log.info(pager);

            Document pagerDoc = Jsoup.parseBodyFragment(pager);
            Element rightArrow = pagerDoc.getElementById("next");

            boolean hasNext = !rightArrow.classNames().contains("disable");

            initList = getList(content, search, site);
            List<Result> otherList = new ArrayList<>();
            while (hasNext) {
                page.click("#next");
                page.waitForTimeout(2500);

                content = page.innerHTML("#allsea_comm");

                otherList = getList(content, search, site);
                initList.addAll(otherList);

                pager = page.innerHTML("#DivPages");
                pagerDoc = Jsoup.parseBodyFragment(pager);
                rightArrow = pagerDoc.getElementById("next");
                hasNext = !rightArrow.classNames().contains("disable");
            }

        } catch (RuntimeException e) {
            log.info("SITE FJ FAILED");
        }

        log.info("#############END FETCH FROM FJ##########");
        log.info("*************FOUND NEW PRODUCTS!!!******************");
        log.info("TOTALLY " + Integer.toString(initList.size()) + "RECORDS HAS BEEN FOUND");
        log.info("*************FOUND NEW PRODUCTS!!!******************");
        return initList;
    }

    public static List<Result> getList(String content, SearchDTO search, Site site) {

        List<Result> list = new ArrayList<>();

        // String wait = page.textContent(".spxsjSpanCss");
        // log.info("**********WAIT HERE FOR 1500MS****************");

        Document doc = Jsoup.parseBodyFragment(content);
        Element body = doc.body();

        Elements lis = body.getElementsByTag("li");

        if (lis.size() == 0) {
            log.info("**********FJ HAVE NO RESULTS FROM WORM**************");
            return list;
        }

        for (Element li : lis) {
            // log.info("***************************************************");
            String pName = li.getElementsByClass("flex_name").first().text();
            // log.info("商品名是:" + pName);
            String sourcePrice = li.getElementsByClass("spxsjSpanCss").first().text();
            String sourcePriceClean = StrUtil.removePrefix(sourcePrice, "￥");
            // log.info("价格是:" + sourcePriceClean);
            // String amountLeft = li.getElementsByClass("flex_hei").first().text();

            Double priceDouble = NumberUtil.isNumber(sourcePriceClean) ? Double.parseDouble(sourcePriceClean) : 0;
            // log.info("数字价格是:" + priceDouble.toString());

            // log.info("剩余数量是:" + amountLeft);
            // String sourceCode = li.getElementsByClass("flex_p").get(1).text();
            // String sourceCodeClean = StrUtil.split(sourceCode, "：")[1];
            // log.info("商品编码是:" + sourceCodeClean);
            String sourceProp = li.getElementsByClass("flex_p").get(2).text();
            String sourcePropClean = StrUtil.split(sourceProp, "：")[1];
            // log.info("商品规格是:" + sourcePropClean);
            String sourceProducer = li.getElementsByClass("flex_p").get(3).text();
            // log.info("商品制造厂是:" + sourceProducer);
            String orderUrl = li.getElementsByTag("a").get(0).attributes().get("href");
            // log.info("商品购买URL是:" + orderUrl);

            // String partnerCode = site.getSiteNo() + sourceCodeClean;

            Result re = new Result();
            re.setKeywordStr(search.getKeywordStr());
            re.setProp(sourcePropClean);
            re.setMaker(sourceProducer);
            re.setProductName(StrUtil.concat(true, pName, ":", sourcePropClean, ":", sourceProducer));
            re.setOrderUrl(StrUtil.concat(true, site.getSiteUrl(), orderUrl));
            re.setScanTime(TimeUtil.currentTime());

            re.setSearchId(search.getId());
            re.setSiteName("福济");
            re.setSiteNo("FJ");
            re.setScanPrice(sourcePriceClean);
            re.setPrice(priceDouble);
            re.setStatus(0);
            list.add(re);

        }

        log.info("SITE FJ SUCCESS");

        return list;
    }
}
